//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Web;
using System.Xml;

namespace CommunityServer.Components
{
	/// <summary>
	/// Updates the last visited date used for thread filters
	/// </summary>
	public class UserLastVisitModule : ICSModule
	{
		public UserLastVisitModule()
		{
		}

		#region ICSModule Members

		public void Init(CSApplication csa, XmlNode node)
		{
			csa.UserKnown +=new CSUserEventHandler(csa_UserKnown);
		}

		#endregion

		/// <summary>
		/// Once a user is known, we can update last visit
		/// </summary>
		private void csa_UserKnown(User user, CSEventArgs e)
		{
			UserCookie userCookie = new UserCookie(user);
			string inMemoryCookieName = "CommunityServer-LastVisitUpdated-" + user.UserID.ToString();
			HttpContext context = HttpContext.Current;

			// See if user's last visit has already been updated
			// NOTE: Only do this the first time thru any session
			HttpCookie cookie = context.Request.Cookies[inMemoryCookieName];

			// This is user's first request of the session
			if (cookie == null)
			{
				// Update user's last visit
				userCookie.UpdateLastVisit();

				// Add in-memory cookie to flag we've already done the update
				cookie = new HttpCookie(inMemoryCookieName);
				context.Response.Cookies.Add(cookie);
			}

			// Always update the cookie with the most recent activity time
			userCookie.UpdateMostRecentActivity();
		}
	}
}
